package com.ask.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Collections;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


public class MyRedisLock {
    private final StringRedisTemplate redisTemplate;
    private final String lockValue;
    private static final long EXPIRE_TIME = 5000;

    public MyRedisLock(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
        this.lockValue = UUID.randomUUID().toString();
    }

    public boolean lock(String lockKey) {
        Boolean success = redisTemplate.opsForValue().
                setIfAbsent(lockKey, lockValue, EXPIRE_TIME, TimeUnit.MILLISECONDS);
        return Boolean.TRUE.equals(success);
    }

    public boolean unlock(String lockKey) {
        // 编写lua脚本
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then " +
                "return redis.call('del', KEYS[1]) else return 0 end";
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>(script, Long.class);
        Long result = redisTemplate.
                execute(redisScript, Collections.singletonList(lockKey), lockValue);
        return Long.valueOf(1).equals(result);
    }
}
